package com.example.demo.handler;

import com.alibaba.druid.util.StringUtils;
import com.example.demo.vo.Result;
import com.example.demo.vo.ResultCode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import java.io.IOException;

/**
 * @author 三石
 */
@Component
@Configuration
public class CaptchaHandler  extends GenericFilterBean {
    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Resource
    private ObjectMapper objectMapper;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setContentType("application/json;charset=utf-8");
        if ("POST".equalsIgnoreCase(request.getMethod()) && "/login".equals(request.getServletPath())) {
            // 获取前端提交的验证码
            String requestCaptcha = request.getParameter("captcha");
            // 从Redis获取验证码
            String genCaptcha = redisTemplate.opsForValue().get("captcha");

            if (StringUtils.isEmpty(requestCaptcha)){
                response.getWriter().write(objectMapper.writeValueAsString(Result.error(ResultCode.CLIENT_A0130)));
                return;
            }
            assert genCaptcha != null;
            if (!genCaptcha.toLowerCase().equals(requestCaptcha.toLowerCase())) {
                response.getWriter().write(objectMapper.writeValueAsString(Result.error(ResultCode.CLIENT_A0131)));
                return;
            }
        }
        filterChain.doFilter(request, response);
    }
}
